//
//  ViewController.m
//  新浪的弹出动画
//
//  Created by MyMac on 15/8/20.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "ViewController.h"
#import "UIImage+ImageEffects.h"
#import <CoreImage/CoreImage.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "FaceViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (weak, nonatomic) IBOutlet UIScrollView *backScroll;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled=YES;
    //所有滤镜种类的名字
    NSArray*filterName=[CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    __weak typeof(self) vc=self;
    ALAssetsLibrary*library=[[ALAssetsLibrary alloc]init];
    UIImage*image=[UIImage imageNamed:@"20081216172223106_2.jpg"];
    self.backScroll.contentSize=CGSizeMake(self.view.bounds.size.width, (filterName.count/3+1)*(self.view.bounds.size.width/3.0));
    CIImage*CIimage=[CIImage imageWithCGImage:image.CGImage];
    //CIContext:使用CPU渲染的IOS会采用GCD来对图像进行渲染，这保证了CPU渲染在大部分情况下更可靠，比CPU渲染更容易使用，他可以在后台实现渲染过程；而GPU渲染方式使用OpenGL ES2.0来渲染图像，这种方式CPU完全没有负担，应用程序的运行循环不会受到图像渲染的影响，而且他渲染比CPU渲染更快但是GPU渲染无法在后台运行。
    //默认情况是用GPU渲染的。
CIContext *context = [CIContext contextWithOptions:nil];//GPU渲染
   // CIContext *context = [CIContext contextWithOptions:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:true] forKey:kCIContextUseSoftwareRenderer]];//CPU渲染,CUP在模拟器上不可用，必须真机
    [filterName enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      
       // NSLog(@"%ld:%@\n%@",(long)idx,obj,attributes);
        CGFloat w=vc.view.bounds.size.width/3.0;
        CGFloat h=w;
        CGFloat x=idx%3*w;
        CGFloat y=idx/3*h;
        UIImageView*imageView=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];
        imageView.userInteractionEnabled=YES;
        [vc.backScroll addSubview:imageView];
      
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, w, 20)];
        label.font=[UIFont systemFontOfSize:12];
        label.textColor=[UIColor redColor];
        label.text=obj;
        [imageView addSubview:label];
        
        
        

            //滤镜渲染也是要耗性能的，，所以在子线程渲染
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                  CIFilter*filter=[CIFilter filterWithName:obj];
                if([[filter attributes].allKeys containsObject:@"inputImage"]){
              
                //滤镜的可设置属性,CoreImage不支持自定义滤镜但提供了127种已知滤镜，通过设置滤镜的属性改变滤镜，滤镜属性是字典
                NSDictionary*attributes=[filter attributes];//滤镜的可设置属性，设置这个字典的key，来设置属性
                [filter setDefaults];
                [filter setValue:CIimage forKey:@"inputImage"];
                CIImage*filterImage=[filter outputImage];
                CGImageRef ref=[context createCGImage:filterImage fromRect:filterImage.extent];
                //写入相册
//                [library writeImageToSavedPhotosAlbum:ref metadata:[filterImage properties] completionBlock:^(NSURL *assetURL, NSError *error) {
//                    NSLog(@"%@",error);
//                    
//                    
//                }];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image=[UIImage imageWithCGImage:ref];
                    CGImageRelease(ref);
                });
            }
                
            });
        
           
            
        

        
        
    }];
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    FaceViewController*face=[[FaceViewController alloc]init];
    [self presentViewController:face animated:YES completion:nil];


}

-(UIImage*)renderScreen
{
    //截屏
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef ctf=UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:ctf];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext()
    ;
    UIGraphicsEndImageContext();
    //[image applyBlurWithRadius:15 tintColor:[UIColor redColor] saturationDeltaFactor:1 maskImage:nil];
    //return [image blurImage];
    return image;


}

-(UIImage*)mohu
{
//模糊效果
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *image = [[CIImage alloc]initWithImage:[self renderScreen]];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:image forKey:kCIInputImageKey];
    [filter setValue:@2.0f forKey: @"inputRadius"];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef outImage = [context createCGImage: result fromRect:[result extent]];
    UIImage * blurImage = [UIImage imageWithCGImage:outImage];
   // UIImage*image1=[UIImage imageWithCIImage:result];
    return blurImage;


}
-(CIImage *)oldPhoto:(CIImage *)img withAmount:(float)intensity {
    
    
    //滤镜链，，，一个照片可连续设置多个滤镜
    
    // 1
    
    CIFilter *sepia = [CIFilter filterWithName:@"CISepiaTone"];
    
    [sepia setValue:img forKey:kCIInputImageKey];
    
    [sepia setValue:@(intensity) forKey:@"inputIntensity"];
    
    
    // 2
    
    CIFilter *random = [CIFilter filterWithName:@"CIRandomGenerator"];
    
    
    // 3
    
    CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
    
    [lighten setValue:random.outputImage forKey:kCIInputImageKey];
    
    [lighten setValue:@(1 - intensity) forKey:@"inputBrightness"];
    
    [lighten setValue:@0.0 forKey:@"inputSaturation"];
    
    
    // 4
    
    CIImage *croppedImage = [lighten.outputImage imageByCroppingToRect:[lighten.outputImage extent]];
    return croppedImage;
}
@end
